import homogenizationConfig from '../../../datas/homogenizationConfig'
import { queryByGeometry, getOnlyResByQueryResult, getAttributesListByQueryResult } from 'lark-map'

const format = async(baseDataList, view, geometry) => {

  if (!baseDataList?.length) {
    throw new Error('查询结果为空')
  }

  let dataList = JSON.parse(JSON.stringify(baseDataList))

  dataList = dataList.filter(item => item?.value?.length)

  if (!dataList?.length) {
    throw new Error('查询结果为空')
  }

  //  数据归并
  dataList = dataList.map(item => item.value).reduce((val1, val2) => {
    return [...val1, ...val2]
  }).reduce((val1, val2) => {
    return Object.assign({}, val1, val2)
  })

  let result = {
    qxtz: {},
    dltz: {},
    trtz: {}
  }

  Object.keys(dataList).forEach(key => {
    let value = isNaN(parseFloat(dataList[key])) ? '' : parseFloat(dataList[key]).toFixed(2)
    switch (key) {
      case '年降雨量_全国':
        console.log('降雨量 = ' + value)
        result.qxtz.ljjy = getResByValue('ljjy', value).value
        result.qxtz.pjsd = getResByValue('pjsd', value / 7.5).value
        result.trtz.trsd = getResByValue('trsd', value / 12).value
        break

      case '年均温度_全国':
        result.qxtz.pjwd = getResByValue('pjwd', value).value
        result.qxtz.ghts = getResByValue('ghts', value * 4.85).value
        break

      case '大于10度积温_全国':
        result.qxtz.yxjw = getResByValue('yxjw', value).value
        break

      case '日照时数_全国':
        result.qxtz.pjrzss = getResByValue('pjrzss', value).value
        break

      case '大风日数_全国':
        result.qxtz.dfts = getResByValue('dfts', value).value
        break

      case '土壤类型':
        result.trtz.trlx = dataList[key]
        break

      case '生态特征':
        result.dltz.hbgd = dataList[key] && dataList[key] !== '' ? (dataList[key].split('，')[1].match(/海拔(\S*)米/) ? dataList[key].split('，')[1].match(/海拔(\S*)米/)[1] : (dataList[key].split('，')[1].match(/在(\S*)之间/) ? dataList[key].split('，')[1].match(/在(\S*)之间/)[1] : '')) : ''
        break

      default:
        break
    }
  })

  await getOtherData(view, geometry, result)

  return result

}

const getOtherData = async(view, geometry, data) => {
  let idList = ['EcoCharacterService']
  let returnGeometry = [{ parentId: 'EcoCharacterService', value: true }]
  let returnFieldName = [{ parentId: 'EcoCharacterService', value: true }]
  let layerOption = [{ parentId: 'EcoCharacterService', value: 'all' }]
  let tolerance = [{ parentId: 'EcoCharacterService', value: 5 }]
  let subLayerIds = [{ parentId: 'EcoCharacterService', value: [0] }]

  let res = await queryByGeometry({
    view,
    idList,
    returnGeometry,
    returnFieldName,
    geometry,
    layerOption,
    tolerance,
    subLayerIds
  })

  let onlyRes = getOnlyResByQueryResult({ res, mapPoint: geometry })

  let aRes = getAttributesListByQueryResult({ res: onlyRes })

  let pdDataList = homogenizationConfig.find(item => item.zbdm === 'pd').dataList
  let pxDataList = homogenizationConfig.find(item => item.zbdm === 'px').dataList
  let stDataList = homogenizationConfig.find(item => item.zbdm === 'styy').dataList
  let hbDataList = homogenizationConfig.find(item => item.zbdm === 'hbgd').dataList

  if (aRes?.length) {
    let [{ SLOPE_DEGREE_GRADE: pd, SLOPE_ASPECT: px, ELEVATION_GRADE: hb }] = aRes

    let [pdMin, pdMax] = pdDataList[pd && parseInt(pd) > 0 ? (parseInt(pd) + 1 > pdDataList.length - 1 ? pdDataList.length - 1 : parseInt(pd) + 1) : 0]
    let [stMin, stMax] = stDataList[pd && parseInt(pd) > 0 ? (parseInt(pd) + 1 > stDataList.length - 1 ? stDataList.length - 1 : parseInt(pd) + 1) : 0]
    let [hbMin, hbMax] = hbDataList[hb && parseInt(hb) > 0 ? (parseInt(hb) + 1 > hbDataList.length - 1 ? hbDataList.length - 1 : parseInt(hb) + 1) : 0]
    data.dltz.pd = `${pdMin} ~ ${pdMax}`
    data.dltz.styy = `${stMin} ~ ${stMax}`
    data.dltz.hbgd = `${hbMin} ~ ${hbMax}`

    if (!px || parseInt(px) === 1) {
      data.dltz.px = '大于 22.5 或 大于 337.5'
    } else {
      let [pxMin, pxMax] = pxDataList[px && parseInt(px) > 0 ? (parseInt(px) + 1 > stDataList.length - 1 ? stDataList.length - 1 : parseInt(px) + 1) + 1 : 0]
      data.dltz.px = `${pxMin} ~ ${pxMax}`
    }
  }
}

const getResByValue = (type, value) => {
  let res = { min: null, value: '', max: null }
  if (type === '' || value === '') return res

  let currentItem = homogenizationConfig.find(item => item.zbdm === type)

  if (value > currentItem.max) {
    res.value = `大于 ${currentItem.max}`
    res.max = currentItem.max
    return res
  }

  if (value < currentItem.min) {
    res.value = `小于 ${currentItem.min}`
    res.min = currentItem.min
    return res
  }

  currentItem.dataList.forEach((item, index) => {
    let [min, max] = item
    if (value >= min && value < max) {
      res.value = `${min} ~ ${max}`
      res.max = max
      res.min = min
      return
    }
  })

  return res
}

export { format }
